package com.nuc.seckill.service.impl;

import com.nuc.seckill.model.SeckillAdmin;
import com.nuc.seckill.security.entity.AdminUser;
import com.nuc.seckill.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * 实际的后台admin用户名和密码验证方法.
 *
 * @author spider
 */
@Service("userDetailsService")
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private AdminService adminService;

    /**
     * 加载用户
     *
     * @param username 用户名
     * @return org.springframework.security.core.userdetails.UserDetails
     * @author 石一歌
     * @date 2022/8/9 22:27
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //获取该用户的信息
        SeckillAdmin seckillAdmin = adminService.selectByUsername(username);
        //用户不存在报错
        if (seckillAdmin == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        AdminUser adminUser = new AdminUser();
        try {
            BeanUtils.copyProperties(seckillAdmin, adminUser);
            adminUser.setUsername(seckillAdmin.getLoginName());
            adminUser.setCreateDate(seckillAdmin.getCreateTime());

            //直接硬写角色，实际中应该是从数据库读取
            dealAdminRoles(adminUser);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        adminUser.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(adminUser.getRoles()));
        return adminUser;
    }

    /**
     * 权限硬编码
     */
    private void dealAdminRoles(AdminUser adminUser) {
        if (adminUser.getUsername().toLowerCase().contains("super")) {
            adminUser.setRoles("ADMIN,SUPERADMIN");
        } else {
            adminUser.setRoles("ADMIN");
        }
    }
}
